<template>
  <!-- 使用v-lazy:background-image指令，将背景图像设置为bg1 -->
  <section v-lazy:background-image="bg1">
    <h1>第一</h1>
  </section>
  <!-- 使用v-lazy:background-image指令，将背景图像设置为bg2 -->
  <section v-lazy:background-image="bg2">
    <h1>第二</h1>
  </section>
  <!-- 使用v-lazy:background-image指令，将背景图像设置为bg3 -->
  <section v-lazy:background-image="bg3">
    <h1>第三</h1>
  </section>
  <!-- 使用v-lazy:background-image指令，将背景图像设置为bg4 -->
  <section v-lazy:background-image="bg4">
    <h1>第四</h1>
  </section>
  <!-- 使用v-lazy:background-image指令，将背景图像设置为bg5 -->
  <section v-lazy:background-image="bg5">
    <h1>第五</h1>
  </section>
</template>

<script setup lang="ts">
// 引入gsap和ScrollTrigger插件
import gsap from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
// 引入背景图像
import bg1 from "/@/assets/images/parallax/bg-1.jpg";
import bg2 from "/@/assets/images/parallax/bg-2.jpg";
import bg3 from "/@/assets/images/parallax/bg-3.jpg";
import bg4 from "/@/assets/images/parallax/bg-4.jpg";
import bg5 from "/@/assets/images/parallax/bg-5.jpg";
// 引入onMounted钩子函数
import { onMounted } from "vue";
// 定义动画函数
const animation = () => {
  // 获取所有section元素
  const sections = document.querySelectorAll("section");
  // 注册ScrollTrigger插件
  gsap.registerPlugin(ScrollTrigger);
  // 遍历所有section元素
  sections.forEach((section) => {
    // 使用gsap.fromTo方法，设置背景图像的垂直位置
    gsap.fromTo(
      section,
      {
        backgroundPositionY: `-${window.innerHeight / 2}px`,
      },
      {
        backgroundPositionY: `${window.innerHeight / 2}px`,
        ease: "none",
        scrollTrigger: {
          trigger: section,
          scrub: true,
        },
      }
    );
  });
};
// 在组件挂载时调用动画函数
onMounted(() => {
  animation();
});
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  width: 100vw;
  height: 100vh;
  overflow-x: auto;
  scroll-snap-type: x mandatory;
}

section {
  flex: 0 0 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  /* 不重复背景图像 */
  background-repeat: no-repeat;

  /* 背景图像覆盖整个元素 */
  background-size: cover;

  /* 背景图像始终位于元素的中心 */
  background-position: center;

  h1 {
    margin: 0;
    /* 设置文字颜色，带有透明度 */
    color: rgba(255, 255, 255, 0.5);
  }
}
</style>
